package com.df.bpm.utils.businessViewer;

import com.df.bpm.entity.EntityType;
import com.df.bpm.utils.businessViewer.entityTypeDialogServices.EntityTypeService;
import com.df.common.utils.CommonUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

public class EntityTypeDialog {

    int unit=10;
    JDialog jd=new JDialog();
    JPanel jp=new JPanel();
    Font iFont;
    EntityType selectResult;
    EntityTypeService entityTypeService;


    public EntityTypeDialog() {
        entityTypeService=new EntityTypeService();
        unit= (int) MainPanel.unit;
        iFont=new Font("宋体", Font.PLAIN, (int) (MainPanel.unit));
        jd.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                // 关闭窗口时触发
            }
        });
        jd.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        jd.setSize(40*unit, 30*unit);
    }

    public EntityType selectEntityType(Integer oldTypeID) {
        if(CommonUtils.varIsBlank(oldTypeID)){
            selectResult=null;
        }else{
            selectResult=entityTypeService.get(oldTypeID);
        }
        repaint4selectDialog();
        return selectResult;
    }

    private void repaint4selectDialog() {
        jd.remove(jp);
        jd.setLocationRelativeTo(null);
        jd.setLayout(null);
        jp=new JPanel();
        jp.setLayout(null);
        jp.setSize(jd.getSize());

        List<JTextField> fields=new ArrayList<>();
        addFields4SelectDialog(fields,"名称");

        JTextField lastField=fields.get(fields.size()-1);
        JScrollPane scr=new JScrollPane();
        scr.setLocation(unit,lastField.getY()+lastField.getHeight()+unit);
        scr.setSize(jp.getWidth()-3*unit, jp.getHeight()-4*unit-scr.getY());
        jp.add(scr);


        for(JTextField field:fields){
            field.addKeyListener(
                    new KeyAdapter(){
                        public void keyPressed(KeyEvent e)
                        {
                            if(e.getKeyChar()==KeyEvent.VK_ENTER )   //按回车键执行相应操作;
                            {
                                search4SelectDialog(fields,scr);
                            }
                        }
                    });
        }

        jd.add(jp);
        jd.setModal(true);
        jd.repaint();
        jd.setVisible(true);

    }

    private void search4SelectDialog(List<JTextField> fields, JScrollPane scr) {
        EntityType temp=new EntityType();
        if (CommonUtils.varIsNotBlank(fields.get(0).getText())) {
            temp.setName(fields.get(0).getText());
        }
        List<EntityType> list = entityTypeService.getList4Like(temp);
        showEntityTypeList4SelectDialog(scr,list);
    }

    private void showEntityTypeList4SelectDialog(JScrollPane scr, List<EntityType> list) {
        scr.getViewport().removeAll();
        String[] title = {"ID","序号", "名称"};
        DefaultTableModel model = new DefaultTableModel(null, title){
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;//不允许编辑，留作触发双击或拖拽
            }
        };
        if(CommonUtils.varIsNotBlank(list)) {
            for (int n=0;n<list.size();n++) {
                EntityType row=list.get(n);
                model.addRow(new Object[]{row.getEntityTypeIndex(),list.size()-n, row.getName()});
            }
        }
        model.addRow(new Object[]{null,null, null});
        list.add(new EntityType());
        JTable iTable=newTable4SelectDialog(model, iFont);
        Main.hideCol(iTable,0);
        scr.getViewport().add(iTable);
        iTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = iTable.rowAtPoint(e.getPoint());
                int col = iTable.columnAtPoint(e.getPoint());
                if (row >= 0 ) {
                    if (e.getClickCount() == 2) {// 处理双击事件
//                        System.out.println("Row " + row + "& Col "+col+" double clicked");
                        String typeID=""+iTable.getValueAt(row, 0);
                        if(col==1 && CommonUtils.varIsNotBlank(typeID)){//不为空的双击代表选中
                            selectResult=list.get(row);
                            jd.dispose();//选好窗口消失
                        }else{// 双击空行触发新增 EntityType
                            if(col==2){
                                editTypeDesc(iTable,row,list);
                            }
                        }

                    }
                }
            }
        });

    }

    static JTable newTable4SelectDialog(DefaultTableModel model, Font iFont) {
        JTable iTable = new JTable(model);
        iTable.getTableHeader().setFont(new Font("宋体", Font.BOLD, (int) (MainPanel.unit*1.1)));
        iTable.setFont(iFont);
        iTable.setRowHeight((int) (MainPanel.unit+1));
        iTable.getColumnModel().getColumn(1).setPreferredWidth(10);
        iTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        return iTable;
    }

    private void editTypeDesc(JTable iTable, int row, List<EntityType> list) {
        String oldValue=""+iTable.getValueAt(row, 2);
        String tips="请输入类型名称：";
        String newValue= (String) JOptionPane.showInputDialog(null, tips, "类型名称", JOptionPane.PLAIN_MESSAGE, null, null, oldValue);
        if(newValue!=null && !newValue.isEmpty() && !oldValue.equals(newValue)){
            iTable.setValueAt(newValue,row,2);
            EntityType temp=new EntityType()
                    .setName(newValue);
            entityTypeService.update(temp);
            list.get(row).setName(newValue);
        }
    }



    private void addFields4SelectDialog(List<JTextField> fields, String colName) {
        addFields4SelectDialog(fields, colName, unit, iFont, jp);
    }

    static void addFields4SelectDialog(List<JTextField> fields, String colName, int unit, Font iFont, JPanel jp) {
        JTextField iField=new JTextField();
        iField.setBounds(unit +fields.size()*(7* unit), unit,6* unit, (int) (2.5* unit));
        iField.setFont(iFont);
        iField.setBorder(BorderFactory.createTitledBorder(colName));
        fields.add(iField);
        jp.add(iField);
    }

}
